package com.thinkgem.jeesite.modules.biz.web.api;

import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.biz.form.BizGoodsForm;
import com.thinkgem.jeesite.modules.biz.form.LoginForm;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.enums.ResultEnum;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author : Kyle
 * @date : 2018/8/24 15:18
 */
@Controller
@Slf4j
@RequestMapping("${adminPath}/api/biz/login")
public class LoginApiController extends BaseController {

    @Autowired
    private SystemService systemService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO login(@Valid LoginForm loginForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response){

        if (bindingResult.hasErrors()) {
            log.error("【登录异常】表单校验参数不正确：loginForm => {}", loginForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        ResultVO resultVO = new ResultVO();
        String username = loginForm.getUserName();
        String password = loginForm.getPassword();
        //根据登录名获取用户
        User byLogin = UserUtils.getByLoginName(username);

        if(byLogin != null){
            if(StringUtils.isNotEmpty(byLogin.getPassword())){
                boolean flag = SystemService.validatePassword(password, byLogin.getPassword());
                if (flag){
                    //password手机端接受明文密码
                    byLogin.setPasswordMing(loginForm.getPassword());
                    //password手机端接受密文密码
                    byLogin.setPasswordMi(byLogin.getPassword());
                    return ResultVOUtil.success(byLogin);
                }else{
                    //密码错误
                    resultVO.setCode(1);
                    resultVO.setMsg("密码错误");
                }
            }
        }else{
            //用户名错误
            resultVO.setCode(1);
            resultVO.setMsg("用户名错误");
        }
        return resultVO;
    }

}
